/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.setup.trac.service;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.Date;

import com.setup.trac.dao.DAOService;
import com.setup.trac.pojo.Allegati;
import com.setup.trac.pojo.Evento;
import com.setup.trac.pojo.Profilo;
import com.setup.trac.pojo.StoricoTicket;
import com.setup.trac.pojo.Tickets;
import com.setup.trac.pojo.Utenti;
import com.setup.trac.pojo.condition.AllegatiFinderBySessioneUtenteWeb;
import com.setup.trac.pojo.wrappers.UtentiView;
import javax.mail.Message.RecipientType;
import javax.mail.internet.InternetAddress;
import javax.mail.search.SearchException;

import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessagePreparator;

/**
 * 
 * @author edoardo
 */
public class MailSenderService {

	private JavaMailSender mailSender;
	private SearchService searchService;
	private DAOService daoService;
	private String from;
	private String url;
	private boolean cancellaEventoInviato=false;

	public static final int SEND_ONLY_TO_DEVELOPER = 0;
	public static final int SEND_ONLY_TO_CUSTOMER = 1;
	public static final int SEND_TO_ALL = 2;

	public String getFrom() {
		return from;
	}

	public void setFrom(String from) {
		this.from = from;
	}

	public SearchService getSearchService() {
		return searchService;
	}

	public void setSearchService(SearchService searchService) {
		this.searchService = searchService;
	}

	public JavaMailSender getMailSender() {
		return mailSender;
	}

	public void setMailSender(JavaMailSender mailSender) {
		this.mailSender = mailSender;
	}

	/**
	 * Invia il ticket creato agli utenti del progetto
	 * 
	 * @param tickets
	 */
	public void sendMessage(Evento evento,Tickets tickets, int type) throws Exception {
		Utenti utenteSegnalante = tickets.getUtentiByIdUtente();
		StoricoTicket[] st = getSearchService().findMaxStoricoTicketByTicket(
				new StoricoTicket[0], tickets);
		TracSetupEventMessagePreparator messagePreparator = new TracSetupEventMessagePreparator();
		messagePreparator.setAllegati((Allegati[]) st[0].getAllegatis()
				.toArray(new Allegati[0]));
		messagePreparator.setFrom(getFrom());
		Utenti owner = tickets.getUtentiByIdOwner();
		if (owner == null) {
			// il ticket non è ancora preso in carico. Segnalo il baco a tutti
			// gli sviluppatori assegnati al progetto
			Profilo p = searchService.findProfiloByDescrizione("DEVELOPER");
			UtentiView[] uv = searchService
					.findUtentiAbilitatiProgettoByProfilo(tickets
							.getIdProgetto().toPlainString(), p);
			for (int i = 0; i < uv.length; i++) {
				UtentiView utentiView = uv[i];
				messagePreparator.addRecipient(RecipientType.TO, new InternetAddress(utentiView
						.getUtenti().getEmail()));
			}
		} else {
			messagePreparator.addRecipient(RecipientType.TO, new InternetAddress(owner
					.getEmail()));
		}

		if (type != SEND_ONLY_TO_DEVELOPER) {
			messagePreparator.addRecipient(RecipientType.TO, new InternetAddress(
					utenteSegnalante.getEmail()));
		}
		OutputStream out = new ByteArrayOutputStream();
		ObjectOutputStream ser = new ObjectOutputStream(out);
		ser.writeObject(tickets);
		URL url = new URL(getUrl());
		URLConnection con = url.openConnection();
		con.setAllowUserInteraction(false);         
		con.setDoOutput(true);
		con.setDoInput(true);
		con.addRequestProperty("Content-Type", "application/octet-stream");

		OutputStream serverOut = con.getOutputStream();
		serverOut.write(((ByteArrayOutputStream) out).toByteArray());
		InputStream in = con.getInputStream();
		byte[] buffer = new byte[2048];
		ByteArrayOutputStream bout = new ByteArrayOutputStream();
		int ch = 0;
		while ((ch = in.read(buffer)) > 0) {
			bout.write(buffer, 0, ch);
		}
		in.close();
		bout.flush();
		bout.close();
		String msg =new String(bout.toByteArray());
		
		messagePreparator.setMessage(msg);

		mailSender.send(messagePreparator);
		
		messagePreparator.setMessageId(messagePreparator.getMimeMessage().getHeader("Message-ID")[0]);
		
		evento.setEmailMessageId(messagePreparator.getMessageId());
		evento.setDataInvio(new Date());
		evento.setInviato("1");
		
		if(!isCancellaEventoInviato()){
			daoService.update(evento);
		}else{
			daoService.delete(evento);
		}
		
		

	}
	
	public void sendMessage(Utenti utente,String url)  throws Exception {
		TracSetupCreateUserMessagePreparator messagePreparator = new TracSetupCreateUserMessagePreparator(utente,url);
		messagePreparator.setFrom(getFrom());
		mailSender.send(messagePreparator);
	}

	public String getUrl() {
		return url;
	}

	public void setUrl(String url) {
		this.url = url;
	}

	public DAOService getDaoService() {
		return daoService;
	}

	public void setDaoService(DAOService daoService) {
		this.daoService = daoService;
	}

	public boolean isCancellaEventoInviato() {
		return cancellaEventoInviato;
	}

	public void setCancellaEventoInviato(boolean cancellaEventoInviato) {
		this.cancellaEventoInviato = cancellaEventoInviato;
	}
}
